
#include "XBeeResponse.h"
#include "XBeeSerial.h"

XBeeResponse::XBeeResponse(char* bytes, int len) : XBeeMessage() {

    rawData = new char[len];
    rawDataLength = len;
    
    for(int i=0; i < len; i++)
        rawData[i] = bytes[i];
    
    apiID = bytes[0];
    int curByte = 1;

    // RX responses do not have Frame IDs, everything else does
    if (apiID != RESP_RX_16BIT && apiID != RESP_RX_64BIT)
    {
        frameID = bytes[curByte++];
    }

    if (apiID == RESP_AT_REMOTE || apiID == RESP_RX_64BIT)
    {
        char* addr = getSubArray(bytes, curByte, 8);
        set64BitAddress(bytesToInt64(addr));
        curByte += 8;
        delete addr;
    }

    if (apiID == RESP_AT_REMOTE || apiID == RESP_RX_16BIT)
    {
        char* addr = getSubArray(bytes, curByte, 2);
        set16BitAddress(bytesToInt16(addr));
        curByte += 2;
        delete addr;
    }

    msgDataLength = len - curByte - 1;
    
    msgData = new char[msgDataLength];

    for (int i = 0; i < msgDataLength; i++)
    {
        msgData[i] = bytes[i + curByte];
    }

    checksumFailed = !verifyChecksum(bytes[len - 1]);
}

bool XBeeResponse::verifyChecksum(char cs) {
    return ((char)(getMessageSum() + cs) == 0xFF);
}

XBeeResponse::~XBeeResponse() {
    
}
